﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Workflow.Domain.Models;
using Workflow.Infrastructure.IRepository;

namespace Workflow.Infrastructure.Repository
{
    public class BaseRepository<T>: IBaseRepository<T> where T : BaseEntity
    {
        private readonly MyDbContext context;
        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="context"></param>
        public BaseRepository(MyDbContext context)
        {
            this.context = context;
        }
        /// <summary>
        /// 表达式单条件查询
        /// </summary>
        /// <param name="exp"></param>
        /// <returns></returns>
        public async Task<T> GetValue(Expression<Func<T, bool>> exp)
        {
            return await context.Set<T>().FirstOrDefaultAsync(exp);
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        public async Task<int> AddRange(params T[] arr)
        {
            await context.Set<T>().AddRangeAsync(arr);
            return await context.SaveChangesAsync();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<int> Delete(params long[] id)
        {
            var entities = context.Set<T>().Where(p => id.Contains(p.Id));
            context.Set<T>().RemoveRange(entities);
            return await context.SaveChangesAsync();
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetAll()
        {
            return context.Set<T>().AsQueryable();
        }
        /// <summary>
        /// 根据id查询数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<T?> GetModel(long id)
        {
            return context.Set<T>().FirstOrDefault(p => p.Id == id);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        public async Task<int> UpdateRange(params T[] arr)
        {
            context.Set<T>().UpdateRange(arr);
            return await context.SaveChangesAsync();
        }
    }
}
